package com.qianfeng.smartplatform.backupclass;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartplatform.pojo.SysHumiture;
import com.qianfeng.smartplatform.service.SysHumitureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Jackiechan on 2022/6/1 14:46
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */

public class MyDHT11HandlerBackup extends TextWebSocketHandler {
    private static Map<String, Long> heartbeatTime = new ConcurrentHashMap<>();

    private SysHumitureService sysHumitureService;

    @Autowired
    public void setSysHumitureService(SysHumitureService sysHumitureService) {
        this.sysHumitureService = sysHumitureService;
    }

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private static Map<String, WebSocketSession> allClient = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String uri = session.getUri().toString();//我们请求的什么地址建立的连接 ,比如/websocket/zhangsan
        //我们约定,最后一个/后的内容就是你是谁
        String name = uri.substring(uri.lastIndexOf("/") + 1);
        session.getAttributes().put("name", name);//把名字保存到了会话中
        //如果之前有会话应该先关闭再添加
        WebSocketSession currentSession = allClient.get(name);
        //如果之前存在连接就先关闭
        if (currentSession != null && currentSession.isOpen()) {
            currentSession.close();
        }
        //保存起来
        allClient.put(name, session);
        System.err.println("MyDHT11Handler中的方法afterConnectionEstablished 执行了");
        super.afterConnectionEstablished(session);
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        /获取到传递过来的温湿度的json数据
        String humtepJson = message.getPayload();
        System.err.println("MyDHT11Handler中的方法handleTextMessage 执行了" + humtepJson);
        //收到的都是温湿度的数据,我们需要保存到数据库中
        SysHumiture sysHumiture = objectMapper.readValue(humtepJson, SysHumiture.class);
        //设置设备的id
        sysHumiture.setDeviceId((String) session.getAttributes().get("name"));
        //设置上传数据的时间
        sysHumiture.setUploadTime(new Date());
        sysHumitureService.addsysHumiture(sysHumiture);
        //记录时间
        Object deviceId = session.getAttributes().get("name");
        heartbeatTime.put((String) deviceId, System.currentTimeMillis());
    }

    /**
     * 当客户端和我们关闭连接之后执行,正在关闭的会话
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object deviceId = session.getAttributes().get("name");
        allClient.remove(deviceId);//移除了会话
        heartbeatTime.remove(deviceId);
    }

}
